package com.amigo.online.provider.user.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import com.amigo.online.common.base.message.entity.MIMCJsonResponse;
import com.amigo.online.common.base.message.enums.MIMCUrlEnum;
import com.amigo.online.common.base.message.util.MIMCHttpUtil;
import com.amigo.online.common.base.security.LocalUser;
import com.amigo.online.common.core.response.Result;
import com.amigo.online.provider.user.util.IMBlackUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.amigo.online.common.base.service.BaseService;
import com.amigo.online.common.core.response.StatusCode;
import com.amigo.online.common.param.RedisKey;
import com.amigo.online.common.param.result.BlackUserInfo;
import com.amigo.online.common.param.result.UserInfo;
import com.amigo.online.provider.user.common.GlobalController;
import com.amigo.online.provider.user.common.RwRedisService;
import com.amigo.online.provider.user.exception.UserException;
import com.amigo.online.provider.user.mapper.BlackMapper;
import com.amigo.online.provider.user.mapper.UserMapper;
import com.amigo.online.provider.user.model.entity.Black;
import com.amigo.online.provider.user.model.entity.User;
import com.amigo.online.provider.user.service.BlackService;
import org.springframework.web.client.RestTemplate;

@Service
@Transactional(rollbackFor = Exception.class)
@SuppressWarnings({"unchecked"})
@Slf4j
public class BlackServiceImpl extends BaseService<Black> implements BlackService {

    @Autowired
    private BlackMapper blackmapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    RwRedisService rwRedisService;

    public static String black_key = RedisKey.USER_BLACK_REDIS_KEY;

    public static String blackList = "blackId";

    public static String blackedList = "blackedId";

    @Override
    public List<BlackUserInfo> getBlackList(Integer page, Integer size) {
        List<BlackUserInfo> bulist = new ArrayList<BlackUserInfo>();
        page = GlobalController.checkPage(page, size);
        UserInfo userInfo = GlobalController.getNowUser();
        Long id = userInfo.getId();
        //获得举报id
        Long tipoff = (long) ((page - 1) * size);
        List<Black> list = blackmapper.findBlackListById(id, tipoff, size);
        if (list.size() == 0) {
            return bulist;
        }
        List<Long> idlist = list.stream().map(e -> e.getBlackUserId()).collect(Collectors.toList());
        List<User> userlist = userMapper.findByIdList(idlist);
        for (Black black : list) {
            for (User user : userlist) {
                if (black.getBlackUserId().equals(user.getId())) {
                    BlackUserInfo bl = new BlackUserInfo(black.getBlackUserId(), user.getAvatar(), user.getNickname(), black.getCreateTime());
                    bulist.add(bl);
                }
            }
        }
        return bulist;
    }

    @Override
    public Boolean blackUser(Long userId) {
        //发送IM拉黑消息
        ResponseEntity<MIMCJsonResponse> responseEntity =  IMBlackUtil.addBlacklistMessage(userId.toString());
        if(responseEntity.getBody().getCode()!=200){
            return false;
        }
        Long time = System.currentTimeMillis() / 1000;
        UserInfo userInfo = GlobalController.getNowUser();
        Long id = userInfo.getId();
        User users = new User();
        users.setId(userId);
        User user = userMapper.selectByPrimaryKey(users);
        if (user == null) {
            throw new UserException(StatusCode.USER_EXCEPTION);
        }
        Black record = new Black();
        record.setUserId(id);
        record.setBlackUserId(userId);

        Black black = blackmapper.findById(id, userId);
        if (black != null) {
//            if (black.getStatus() == 1) {//被拉黑时不能拉黑别人
//                throw new UserException(StatusCode.ACCOUNT_ISBLACK);
//            } else {
            black.setStatus(1);
            black.setUpdateTime(time);
            if (blackmapper.updateStatus(black.getId(), time, 1) != 1) {
                throw new UserException(StatusCode.INTERNAL_SERVER_ERROR);
            }
//            }
        } else {
            record.setStatus(1);
            record.setCreateTime(time);
            record.setUpdateTime(time);
            if (blackmapper.insert(record) != 1) {
                throw new UserException(StatusCode.INTERNAL_SERVER_ERROR);
            }
        }
        //存缓存
        HashMap<String, TreeSet<Long>> map, maped = null;
        if (rwRedisService.hhasKey(black_key, id)) {
            map = (HashMap<String, TreeSet<Long>>) rwRedisService.hget(black_key, id);
        } else {
            map = new HashMap<String, TreeSet<Long>>();
        }
        if (rwRedisService.hhasKey(black_key, userId)) {
            maped = (HashMap<String, TreeSet<Long>>) rwRedisService.hget(black_key, userId);
        } else {
            maped = new HashMap<String, TreeSet<Long>>();
        }
        TreeSet<Long> list = map.get(blackList);
        TreeSet<Long> listed = map.get(blackedList);
        if (list == null || listed == null) {
            list = new TreeSet<Long>();
            listed = new TreeSet<Long>();
            list.add(userId);
            map.put(blackList, list);
            map.put(blackedList, listed);
        } else {
            if (!list.contains(userId)) {
                list.add(userId);
                map.put(blackList, list);
            }
        }
        TreeSet<Long> userIdlist = maped.get(blackList);
        TreeSet<Long> userIdlisted = maped.get(blackedList);
        if (userIdlist == null || userIdlisted == null) {
            userIdlist = new TreeSet<Long>();
            userIdlisted = new TreeSet<Long>();
            userIdlisted.add(id);
            maped.put(blackList, userIdlist);
            maped.put(blackedList, userIdlisted);
        } else {
            if (!userIdlisted.contains(id)) {
                userIdlisted.add(id);
                maped.put(blackedList, userIdlisted);
            }
        }
        rwRedisService.hput(black_key, id, map);
        rwRedisService.hput(black_key, userId, maped);
        return true;
    }

    @Override
    public Boolean cancelBlackUser(Long userId) {

        //发送IM取消拉黑消息
        ResponseEntity<MIMCJsonResponse> responseEntity =  IMBlackUtil.deleteBlacklistMessage(userId.toString());
        if(responseEntity.getBody().getCode()!=200){
            return false;
        }
//        Long time = System.currentTimeMillis() / 1000;
//        UserInfo userInfo = GlobalController.getNowUser();
//        Long id = userInfo.getId();
//        User user = userMapper.selectByPrimaryKey(userId);
//        if (user == null) {
//            throw new UserException(StatusCode.BAD_REQUEST);
//        }
//        Black black = blackmapper.findById(id, userId);
//        if (black == null) {
//            throw new UserException(StatusCode.BAD_REQUEST);
//        }
//        if (black.getStatus() == 0) {
//            throw new UserException(StatusCode.BAD_REQUEST);
//        }
//        black.setUpdateTime(time);
//        if (blackmapper.updateStatus(black.getId(), time, 0) != 1) {
//            throw new UserException(StatusCode.INTERNAL_SERVER_ERROR);
//        }
//        //存缓存
//        HashMap<String, TreeSet<Long>> map, maped = null;
//        if (rwRedisService.hhasKey(black_key, id)) {
//            map = (HashMap<String, TreeSet<Long>>) rwRedisService.hget(black_key, id);
//        } else {
//            map = new HashMap<String, TreeSet<Long>>();
//        }
//        if (rwRedisService.hhasKey(black_key, userId)) {
//            maped = (HashMap<String, TreeSet<Long>>) rwRedisService.hget(black_key, userId);
//        } else {
//            maped = new HashMap<String, TreeSet<Long>>();
//        }
//        TreeSet<Long> list = map.get(blackList);
//        TreeSet<Long> listed = map.get(blackedList);
//        if (list == null || listed == null) {
//            list = new TreeSet<Long>();
//            listed = new TreeSet<Long>();
//            map.put(blackList, list);
//            map.put(blackedList, listed);
//        } else {
//            if (list.contains(userId)) {
//                list.remove(userId);
//                map.put(blackList, list);
//            }
//        }
//        TreeSet<Long> userIdlist = maped.get(blackList);
//        TreeSet<Long> userIdlisted = maped.get("blackedId");
//        if (userIdlist == null || userIdlisted == null) {
//            userIdlist = new TreeSet<Long>();
//            userIdlisted = new TreeSet<Long>();
//            maped.put("blackId", userIdlist);
//            maped.put("blackedId", userIdlist);
//        } else {
//            if (userIdlisted.contains(id)) {
//                userIdlisted.remove(id);
//                maped.put(blackedList, userIdlisted);
//            }
//        }
//        rwRedisService.hput(black_key, id, map);
//        rwRedisService.hput(black_key, userId, maped);
        return true;
    }

//    /**
//     *
//     * @param id 当前用户ID
//     * @param bid 查询用户ID
//     * @return
//     */
//    @Override
//    public Boolean isblack(Long id, Long bid) {
//        HashMap<String, TreeSet<Long>> map = null;
//        if (rwRedisService.hhasKey(black_key, id)) {
//            map = (HashMap<String, TreeSet<Long>>) rwRedisService.hget(black_key, id);
//        }
//        if (map == null) {
//            Black black = blackmapper.findById(id, bid);
//            if (black == null) {
//                return false;
//            } else {
//                if (black.getStatus() == 1) {
//                    return true;
//                } else {
//                    return false;
//                }
//            }
//        } else {
//            if (map.get(blackList) != null && map.get(blackList).contains(bid)) {
//                return true;
//            }
//            return false;
//        }
//    }




    /**
     * 发送查看我是否把别人拉黑消息
     * @param userId
     * @return
     */
    private ResponseEntity<MIMCJsonResponse> selectBlacklistMessage(Long userId){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("blackAccount", userId);
        HttpEntity<JSONObject> requestEntity = new HttpEntity<JSONObject>(null, MIMCHttpUtil.getUserHttpHeaders());
        RestTemplate restTemplate =new RestTemplate();
        ResponseEntity<MIMCJsonResponse> responseEntity =  restTemplate.exchange(MIMCUrlEnum.SELECT_BLACKLIST.getValue()+userId, HttpMethod.GET, requestEntity , MIMCJsonResponse.class);
        log.debug("发送查看是否拉黑返回值: " + responseEntity.getBody());
        return responseEntity;
    }

    /**
     * 发送查看别人是否把我拉黑消息
     * @param myUserId 我的userID
     * @param heUserId
     * @return
     */
    private ResponseEntity<MIMCJsonResponse> selectBlacklistMessage(Long myUserId,Long heUserId){

        HttpEntity<JSONObject> requestEntity = new HttpEntity<JSONObject>(null, MIMCHttpUtil.getUserHttpHeaders(heUserId.toString()));
        RestTemplate restTemplate =new RestTemplate();
        ResponseEntity<MIMCJsonResponse> responseEntity =  restTemplate.exchange(MIMCUrlEnum.SELECT_BLACKLIST.getValue()+myUserId, HttpMethod.GET, requestEntity , MIMCJsonResponse.class);
        log.debug("发送查看是否拉黑返回值: " + responseEntity.getBody());
        return responseEntity;
    }
    /**
     * 我有没有把对方拉黑
     * @param userId 对方id
     * @return
     */
    @Override
    public Boolean isblack(Long userId) {
        ResponseEntity<MIMCJsonResponse> responseEntity = selectBlacklistMessage(userId);
        if(responseEntity.getStatusCode().equals(HttpStatus.OK)){
            if(responseEntity.getBody().getCode() != 200){
                throw new UserException();
            }else {
                return responseEntity.getBody().getData().getBoolean("isBlack");
            }
        }else {
            throw new UserException();
        }
    }
    /**
     * 对方有没有把我拉黑
     * @param heUserId 对方id
     * @return
     */
    @Override
    public Boolean sufferBlack(Long heUserId) {
        Long myUserId = LocalUser.getUser().getUser().getId();
        ResponseEntity<MIMCJsonResponse> responseEntity = selectBlacklistMessage(myUserId, heUserId);
        if(responseEntity.getStatusCode().equals(HttpStatus.OK)){
            if(responseEntity.getBody().getCode() != 200){
                throw new UserException();
            }else {
                return responseEntity.getBody().getData().getBoolean("isBlack");
            }
        }else {
            throw new UserException();
        }
    }
}
